<template>
  <div class="previewImg" @click="dialogVisible = true">
    <slot>
      <img :src="props.src" alt="图片加载失败" />
    </slot>
  </div>
  <el-dialog v-model="dialogVisible" title="查看图片" @close="close">
    <img :src="imgSrc" alt="Preview Image" style="max-width: 100%" />
  </el-dialog>
</template>

<script setup lang="ts" name="PreviewImage">
import { ref, onMounted, useSlots } from 'vue'
import { ElDialog } from 'element-plus'

const props = defineProps({
  src: String
})

const dialogVisible = ref(false)
const imgSrc = ref('')
const slots = useSlots()

onMounted(() => {
  let slot = slots?.default?.()  
  if (slot) {
    imgSrc.value = slot?.[0]?.props?.src
  }
})

const setSrc = (v: string) => {
  imgSrc.value = v
}

// 组件触发
if (props.src) {
  setSrc(props.src)
}

// 指令触发
const show = () => {
  dialogVisible.value = true
}

const close = () => {
  if (document.getElementById('previewDom')) {
    document.body.removeChild(document.getElementById('previewDom') as HTMLElement)
  }
}

defineExpose({
  show,
  setSrc
})
</script>

<style scoped lang="less">
.previewImg {
  cursor: zoom-in;
  position: relative;
  display: inline-flex;
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
  }
  &:hover {
    &::after {
      opacity: 1;
    }
  }
}
</style>
